<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AdminBundle\Entity\SymbolAmplitude;

class AmplitudeController extends HuobiKlineBaseController
{
    const CACHE_KLINE_KEY = 'list:kline_30min';

    /**
     * 相对于BTC各币的振幅比例
     * @Route("/kline_30min_btc_amplitude", name="kline_30min_btc_amplitude")
     */
    public function amplitude30minAction(Request $request)
    {
        $content = $request->getContent();

        $data = json_decode($content, true);

        if ($data == null || !isset($data['ch']) || !isset($data['tick'])) {
            return $this->apiResult(1, 'empty data.', $content);
        }
// -------------------------------------------------------------------------------
//        $data = $data ?: [];
//        $data_default = ["ch" => 'market.btcusdt.kline.1min', "ts" => time(),
//            "tick" => ["id" => time(), "open" => 0, "close" => 0, "low" => 0,
//                "high" => 0, "amount" => 0, "vol" => 0, "count" => 0]
//        ];
//        $data = array_replace_recursive($data_default, $data);
// -------------------------------------------------------------------------------

        $coin = explode('.', $data['ch'])[1];
        $tick = $data['tick'];

        $datetime = new \DateTime();
        $timestamp = $tick['id'];
        $datetime->setTimestamp($timestamp);

        $data_now = [
            // KLine
            'open' => $tick['open'],
            'close' => $tick['close'],
            'low' => $tick['low'],
            'high' => $tick['high'],
            'amount' => $tick['amount'],
            'vol' => $tick['vol'],
            'count' => $tick['count'],
            'time' => $datetime,
            'time_stamp' => $timestamp,
        ];

        $em = $this->getDoctrine()->getManager();
        // 获取近10个数据
        $data = $this->getKline($coin, $timestamp, 60);

        // 计算数据：统计汇总
        $result = $this->analysis($coin, $data);

        if (empty($result)) {
            return new Response('empty analysis result.');
        }

        if ($coin == 'btcusdt') {
            $btcValue = new SymbolAmplitude();
            $btcValue->setBtcUp5Ration($result['up_5_ratio'])
                ->setBtcDown5Ratio($result['down_5_ratio']);
        } else {
            $btcValue = $em->getRepository('AdminBundle:SymbolAmplitude')->findOneBy([
                'coin' => 'btcusdt', 'timeStamp' => $timestamp, 'period' => '30min']);
            if (empty($btcValue)) {
                return new Response('error');
            }
        }

        $symbolAmplitude = new SymbolAmplitude();
        $symbolAmplitude->setCoin($coin)
            ->setPeriod('30min')
            ->setTimeStamp($timestamp)
            ->setCtime(new \DateTime())
            ->setBtcUp5Ration($btcValue->getBtcUp5Ration())
            ->setBtcDown5Ratio($btcValue->getBtcDown5Ratio())
            ->setUp5Ratio($result['up_5_ratio'])
            ->setDown5Ratio($result['down_5_ratio']);
        $em->persist($symbolAmplitude);
        $em->flush();

        return new Response('ok');
    }

    protected function KlineInstance($data_now, $prefix)
    {
        $huobiMarketKline30min = new HuobiMarketKline30min($data_now, $prefix);
        return $huobiMarketKline30min;
    }

    protected function getKline($coin, $timestamp = 0, $duration = 60)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository('AdminBundle:HuobiMarketKline30min')->get60mins($coin, $timestamp, $duration);
        return $data;
    }

    protected function klinePeriod()
    {
        $kline_multiple = [
            "5" => 5,];

        return $kline_multiple;
    }

    protected function KlineCalcInstance($data)
    {
        $huobiCalcKline30min = new HuobiCalcKline30min($data);
        return $huobiCalcKline30min;

    }

    protected function cacheKey()
    {
        return self::CACHE_KLINE_KEY;
    }

    protected function calcKlineMinSize()
    {
        $min_size = parent::calcKlineMinSize() - 1;
        return $min_size;
    }

}
